<template>
  <a-scrollbar style="height: 370px; overflow: auto">
    <div class="new-collertion-con">
      <div class="common-text">{{ taskDesc }}</div>
      <div class="mt10">任务基础信息</div>
      <BasicTaskInfo ref="basicTaskInfo" type="NEW_PRODUCT_PICTURE" :price="dataObj.hasNoOriginalPic ? getPrice() : amtCost" />
      <div class="required mt10">是否已有产品原图</div>
      <a-space>
        <a-radio-group v-model="dataObj.hasNoOriginalPic">
          <a-radio :value="true">
            <span>没有原图</span>
          </a-radio>
          <a-radio :value="false">
            <span>已有原图</span>
          </a-radio>
        </a-radio-group>
      </a-space>
      <div class="mt10" v-if="dataObj.hasNoOriginalPic">
        <div class="required">产品原图</div>
        <a-radio-group style="width: 100%" v-model="dataObj.outOriginalType">
          <div class="product-artwork">
            <div class="left">
              <div class="radio-box">
                <a-radio value="REAL_SHOOT"></a-radio>
              </div>
              <div class="desc">
                <div class="clearfix">
                  <span class="fl">实物拍摄出原图</span>
                  <span class="fr" style="color: red"> 服务费 ￥{{ configInfo.amtServiceRealShoot }}/单 </span>
                </div>
                <div class="common-text">任务被接单之后，需要将样品送到任务承接方，对方收到样品方可开始任务</div>
              </div>
            </div>
            <div class="right">
              <div class="radio-box">
                <a-radio :disabled="!cadList[0]" value="C4D_RENDER"> </a-radio>
              </div>
              <div class="desc">
                <div class="clearfix">
                  <span class="fl">CAD渲染出原图</span>
                  <span v-if="props.type == 'add'" class="ml10 highlight cursor fl" @click="props.searchSku()"><icon-sync /></span>
                  <span class="fr" style="color: red">服务费 ￥{{ configInfo.amtServiceC4dRender }}/单</span>
                </div>
                <div class="common-text">渲染需要有产品CAD文件，生成产品原图片，用于精修橱窗图</div>
                <div class="common-text">CAD文件从产品上获取，如果没有，请先在产品上上传CAD文件，再来发布任务</div>
                <div class="have-cad" v-if="cadList[0]">
                  <a-space style="width: 100%" v-for="item of cadList">
                    <div class="img-box">
                      <img src="@/assets/CAD.png" alt="" />
                    </div>
                    <div>
                      <div>CAD文件</div>
                      <div class="common-text">{{ item.name }}</div>
                    </div>
                  </a-space>
                </div>
                <div class="common-text no-cad-text" v-else>
                  <div><icon-exclamation-circle-fill style="font-size: 20px" /></div>
                  <div class="common-text">该产品没有CAD文件无法选择该项</div>
                </div>
              </div>
            </div>
          </div>
        </a-radio-group>
      </div>
      <div class="mt10" v-else>
        <div>
          <span class="required">上传产品原图</span>
          <span class="common-text ml10">产品原图是修产品橱窗图的基础</span>
        </div>
        <div class="product-img-box">
          <div class="box">
            <div class="box-img-con" v-for="(item, index) of dataObj.originalPicList" :key="index">
              <div class="mask">
                <div class="btn-con">
                  <icon-eye class="cursor" style="margin-right: 15px" @click="showImgPre(index)" />
                  <icon-delete class="cursor" @click="dataObj.originalPicList.splice(index, 1)" />
                </div>
              </div>
              <a-image :src="item.url" width="100%" height="100%" />
            </div>
            <div class="fl" style="width: 80px; height: 80px" v-loading="uplaodfixPicLoading">
              <a-upload class="fl" :show-file-list="false" list-type="picture-card" action="/" :on-before-upload="beforeUplaodfixPic" />
            </div>
          </div>
        </div>
      </div>
      <div class="mt10">
        <span>其他附件</span>
        <span class="common-text ml10">如果还有其他跟任务相关的资料就在此上传相关任务</span>
      </div>
      <div class="upload-con clearfix">
        <div class="left fl" v-loading="uploadLoading">
          <a-upload class="fl" :show-file-list="false" action="/" :on-before-upload="beforeUplaod">
            <template #upload-button>
              <div class="custom-uplaod-btn">
                <icon-plus />
              </div>
            </template>
          </a-upload>
        </div>
        <div class="right fl">
          <ul>
            <li v-for="(item, index) of dataObj.attachmentList" :key="item">
              <span>{{ item.name ? item.name : getName(item.url) }}</span>
              <span class="cursor icon-del" @click="dataObj.attachmentList.splice(index, 1)"><icon-close /></span>
            </li>
          </ul>
        </div>
      </div>
      <div class="required mt10">
        <span>橱窗图</span>
        <!-- <span style="color: red; margin-left: 10px">合计服务费 ￥{{ amtCost }}</span> -->
      </div>
      <a-checkbox-group v-model="dataObj.imgTypeCode" @change="checkboxChange">
        <div class="img-type-con">
          <div class="img-item" v-for="item of imgTypeList">
            <a-space>
              <a-checkbox :disabled="item.disabled" :value="item.busType"></a-checkbox>
              <div class="img-item-title-text">{{ imgTypeMap[item.busType] }}</div>
              <div class="ml10">服务费:￥{{ item.servicePrice }}/张</div>
            </a-space>
            <a-space style="margin: 5px 0">
              <div>尺寸：</div>
              <div>{{ item.length }}*{{ item.width }}</div>
            </a-space>
            <a-space>
              <div>数量：</div>
              <a-input-number @change="changeNum($event, item)" style="width: 140px" size="mini" :min="1" v-model="item.num" mode="button" />
            </a-space>
          </div>
        </div>
      </a-checkbox-group>
      <div class="ask">
        <a-textarea v-model="dataObj.remark" placeholder="请输入备注" auto-size />
      </div>
    </div>
  </a-scrollbar>
  <a-image-preview-group v-model:visible="visible" v-model:current="current" infinite :srcList="dataObj.originalPicList?dataObj.originalPicList.map((e:any) => e.url):[]" />
</template>

<script lang="ts" setup>
  import { ref, onMounted, reactive, inject, computed, watch } from 'vue'
  import { uploadFile } from '@/api/base'
  import { getPlatTaskConfigByTaskType } from '@/api/task'
  import { OSSUpload } from '@/utils/ossUpload'
  import BasicTaskInfo from './basicTaskInfo.vue'
  import { Message } from '@arco-design/web-vue'
  const props = defineProps(['searchSku', 'configInfo', 'type'])
  const skuInfo: any = inject('skuInfo')
  let dataObj: any = reactive({
    remark: '',
    // amtOriginalService: 0,
    hasNoOriginalPic: true,
    outOriginalType: 'REAL_SHOOT',
    attachmentList: [],
    windowPicList: [],
    imgTypeCode: ['MAIN', 'PANORAMA', 'SPECIAL', 'POSTER', 'SIZE', 'MODEL'],
    originalPicList: [],
  })

  let visible = ref(false)
  let uplaodfixPicLoading = ref(false)
  let current = ref()
  let configInfo: any = ref({})
  let taskDesc = ref('')
  // 基础信息实体
  const basicTaskInfo = ref<any>(null)
  // 橱窗图
  const imgTypeList = ref([
    {
      amtService: 0,
      busType: 'MAIN',
      length: 1600,
      num: 1,
      url: '',
      width: 1600,
      disabled: true,
      servicePrice: 0,
    },
    {
      amtService: 0,
      busType: 'PANORAMA',
      length: 1600,
      num: 1,
      url: '',
      width: 1600,
      disabled: true,
      servicePrice: 0,
    },
    {
      amtService: 0,
      busType: 'SPECIAL',
      length: 1600,
      num: 1,
      url: '',
      width: 1600,
      disabled: true,
      servicePrice: 0,
    },
    {
      amtService: 0,
      busType: 'SIZE',
      length: 1600,
      num: 1,
      url: '',
      width: 1600,
      disabled: false,
      servicePrice: 0,
    },
    {
      amtService: 0,
      busType: 'MODEL',
      length: 1600,
      num: 1,
      url: '',
      width: 1600,
      disabled: false,
      servicePrice: 0,
    },
    {
      amtService: 0,
      busType: 'POSTER',
      length: 1600,
      num: 1,
      url: '',
      width: 1600,
      disabled: false,
      servicePrice: 0,
    },
  ])

  const imgTypeMap = {
    MAIN: '主图',
    PANORAMA: '全景图',
    SPECIAL: '特写图',
    SIZE: '尺寸图',
    MODEL: '模特图',
    POSTER: '海报图',
  }

  const amtCost = computed(() => {
    let list: any = []
    dataObj.imgTypeCode.forEach((item: any) => {
      list.push(imgTypeList.value.find((e: any) => e.busType == item))
    })
    return list.reduce((pre: any, cur: any) => {
      return pre + cur.servicePrice * cur.num
    }, 0)
  })

  let cadList = computed(() => {
    let arr = skuInfo.value?.productSpu?.productInfoList || []
    if (props.type == 'add') {
      return arr.filter((e: any) => e.type == 'CAD')
    } else {
      return skuInfo.value.cadList || []
    }
  })
  // 附件
  let uploadLoading = ref(false)
  const getName = (url: string) => {
    let arr = url.split('/')
    if (arr[0]) return arr[arr.length - 1]
  }

  const beforeUplaod: any = async (file: any) => {
    let formData = new FormData()
    formData.append('file', file)
    uploadLoading.value = true
    try {
      const res: any = await uploadFile(formData)
      if (res) {
        let obj = {
          amtService: 0,
          url: res.data.publicUrl,
          name: file.name,
        }
        dataObj.attachmentList.push(obj)
      }
    } catch (error) {}
    uploadLoading.value = false
  }

  const checkboxChange = () => {
    dataObj.windowPicList = []
    dataObj.imgTypeCode.forEach((element: String) => {
      let item: any = imgTypeList.value.find((item) => item.busType == element)
      // item.amtService = item.num * item.servicePrice
      if (item) dataObj.windowPicList.push(item)
    })
  }
  const changeNum = (val: any, item: any) => {
    if (dataObj.imgTypeCode.indexOf(item.busType) == -1) dataObj.imgTypeCode.push(item.busType)
    checkboxChange()
  }

  const getOrSetInfo = (info?: any) => {
    if (!info) {
      let item = basicTaskInfo.value.getOrSetForm()
      // 校验基础信息必填项
      if (!item) return
      // 校验橱窗图必填
      console.log(dataObj.windowPicList)

      if (!dataObj.hasNoOriginalPic && !dataObj.originalPicList[0]) {
        Message.error('请上传产品原图')
        return false
      }

      if (!dataObj.windowPicList[0]) {
        Message.error('请选择橱窗图')
        return false
      }
      // 根据类型判断是否有服务费
      dataObj.hasNoOriginalPic && (dataObj.amtOriginalService = dataObj.outOriginalType == 'REAL_SHOOT' ? configInfo.value.amtServiceRealShoot : configInfo.value.amtServiceC4dRender)
      // 删除无效字段
      dataObj.hasNoOriginalPic ? delete dataObj.originalPicList : delete dataObj.outOriginalType

      // 处理橱窗图总价

      dataObj.windowPicList.forEach((item: any) => {
        item.amtService = item.num * item.servicePrice
      })
      let obj = {
        ...item,
        amtCost: getPrice(),
        newProductPicTask: dataObj,
      }

      return obj
    } else {
      dataObj.hasNoOriginalPic = info.newProductPicTask.hasNoOriginalPic
      dataObj.originalPicList = info.newProductPicTask?.originalPicList || []
      dataObj.remark = info.newProductPicTask.remark
      dataObj.attachmentList = info.newProductPicTask.attachmentList
      dataObj.outOriginalType = info.newProductPicTask.outOriginalType
      dataObj.imgTypeCode = info.newProductPicTask.windowPicList.map((e: any) => e.busType)
      dataObj.windowPicList = info.newProductPicTask.windowPicList
      dataObj.windowPicList.forEach((item: any) => {
        let index = imgTypeList.value.findIndex((e: any) => e.busType == item.busType)
        if (index != -1) {
          imgTypeList.value[index].num = item.num
        }
        item.servicePrice = item.amtService / item.num
      })
      // getComConfig()
      basicTaskInfo.value.getOrSetForm(info)
    }
  }

  // 获取平台端配置
  const getComConfig = async () => {
    const res: any = await getPlatTaskConfigByTaskType({ taskType: 'NEW_PRODUCT_PICTURE' })
    let amtService = res?.data?.amtService || {}
    configInfo.value = amtService
    taskDesc.value = res?.data?.taskDesc || ''
    imgTypeList.value[0].servicePrice = amtService.amtServiceMainPic
    imgTypeList.value[1].servicePrice = amtService.amtServicePanoramaPic
    imgTypeList.value[2].servicePrice = amtService.amtServiceSpecialPic
    imgTypeList.value[3].servicePrice = amtService.amtServiceSizePic
    imgTypeList.value[4].servicePrice = amtService.amtServiceModelPic
    imgTypeList.value[5].servicePrice = amtService.amtServicePosterPic

    // if (dataObj.windowPicList[0]) {
    //   dataObj.windowPicList.forEach((e: any) => {
    //     let item: any = imgTypeList.value.find((item) => item.busType == e.busType)
    //     if (item) {
    //       e.servicePrice = item.servicePrice
    //     }
    //   })
    // }
  }

  const showImgPre = (index: number) => {
    current.value = index
    visible.value = true
  }

  const getPrice = () => {
    let num = 0
    dataObj.outOriginalType == 'REAL_SHOOT' ? (num = configInfo.value.amtServiceRealShoot) : (num = configInfo.value.amtServiceC4dRender)
    if (dataObj.hasNoOriginalPic) {
      return num + amtCost.value
    } else {
      return amtCost.value
    }
  }

  const beforeUplaodfixPic = async (file: File): Promise<any> => {
    uplaodfixPicLoading.value = true
    const res: any = await OSSUpload(file)
    dataObj.originalPicList.push({ url: res.url })
    uplaodfixPicLoading.value = false
  }

  watch(
    () => skuInfo.value?.productSpu?.productInfoList,
    (val) => {
      if (!val) return
      let arr: any = val.filter((e: any) => e.type == '原图')
      let arrRes = arr.reduce(
        (resArr: any, item: any) => {
          let obj = { url: item.url }
          return [...resArr, obj]
        },
        [...dataObj.originalPicList]
      )
      dataObj.originalPicList = arrRes
    }
  )

  onMounted(() => {
    getComConfig()
    checkboxChange()
  })

  defineExpose({ getOrSetInfo, getPrice })
</script>

<style lang="less" scoped>
  :deep(.arco-checkbox) {
    margin-right: 0 !important;
  }

  :deep(.arco-textarea-wrapper) {
    border: none !important;
  }

  .custom-uplaod-btn {
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
    background: var(--color-fill-2);
    border: 1px dashed var(--color-neutral-3);
    border-radius: var(--border-radius-small);
  }

  .product-img-box {
    overflow: hidden;
    .box {
      margin-top: 5px;
      // min-height: 180px;
      // border-right: 1px solid #d7d7d7;
      .box-img-con {
        float: left;
        width: 80px;
        height: 80px;
        position: relative;
        margin: 0 10px 10px 0;
        &:hover {
          .mask {
            display: block;
          }
        }
        .mask {
          height: 80px;
          width: 80px;
          position: absolute;
          top: 0;
          left: 0;
          display: none;
          z-index: 1;
          background: rgba(0, 0, 0, 0.5);
          .btn-con {
            width: 80px;
            color: white;
            font-size: 18px;
            text-align: center;
            margin-top: 25px;
            align-items: center;
          }
        }
      }
    }
  }

  .ask {
    width: 100%;
    min-height: 100px;
    border: 1px solid #d7d7d7;
    border-radius: 5px;
    padding: 10px;
  }

  .new-collertion-con {
    padding: 5px 0;
    box-sizing: border-box;
    .product-artwork {
      width: 100%;
      display: flex;
      justify-content: space-between;
      .left {
        display: flex;
        width: 49%;
        border: 1px solid #d7d7d7;
        padding: 5px;
      }
      .right {
        display: flex;
        width: 49%;
        // height: 60px;
        border: 1px solid #d7d7d7;
        padding: 5px;
      }
      .radio-box {
        width: 26px;
        text-align: center;
      }
      .desc {
        flex: 1;
      }
    }

    .img-type-con {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      .img-item {
        width: 220px;
        min-height: 100px;
        border: 1px solid #d7d7d7;
        border-radius: 5px;
        padding: 5px;
        font-size: 12px;
        margin-right: 10px;
        margin-bottom: 10px;
        .img-item-title-text {
          width: 40px;
        }
      }
    }
  }
  .common-text {
    font-size: 12px;
    color: #a39999;
  }

  .have-cad {
    .img-box {
      width: 40px;
      height: 40px;
    }
  }
  .no-cad-text {
    margin: 5px 0;
    text-align: center;
  }

  .upload-con {
    .left {
      width: 80px;
    }
    .right {
      margin-left: 20px;
      flex: 1;
      li {
        height: 20px;
        line-height: 20px;
        min-width: 200px;
        background-color: #d7d7d7;
        margin-bottom: 8px;
        font-size: 12px;
        color: #aaaaaa;
        position: relative;
        .icon-del {
          font-size: 12px;
          color: black;
          margin-left: 30px;
          position: absolute;
          right: 10px;
          top: 0;
        }
      }
    }
    .upload-btn-style {
      width: 60px;
      height: 60px;
      border: 1px solid #d7d7d7;
      border-radius: 5px;
      text-align: center;
      line-height: 60px;
      font-size: 26px;
    }
  }
</style>
